package net.zhengxinyun.performance.App.appCtrl;

import com.sirdc.modules.utils.ObjectUtils;
import net.zhengxinyun.performance.App.dto.ScoreDTO;
import net.zhengxinyun.performance.App.dto.report.LeadScoreDTO;
import net.zhengxinyun.performance.App.entity.EvaluateScoreEntity;
import net.zhengxinyun.performance.App.service.EvalScoreMag.EvalScoreMagService;
import net.zhengxinyun.performance.App.service.leaderCriteria.LeaderCriteriaService;
import net.zhengxinyun.performance.Util.DataUtil;
import net.zhengxinyun.performance.Util.StringUtils;
import net.zhengxinyun.performance.core.Result;
import net.zhengxinyun.performance.core.ResultUtils;
import net.zhengxinyun.performance.data.UserAppDTO;
import net.zhengxinyun.performance.filter.LeadersFilter;
import net.zhengxinyun.performance.filter.UserFilter;
import net.zhengxinyun.performance.service.login.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.DataInput;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Date: 2020/3/17 19:12
 */

/**
 * 领导考评的页面
 */
@RestController
@RequestMapping("/app/leaders")
public class NewLeaderScoreCtrl extends BaseCtrl {

    @Autowired
    private UserService userService;

    @Autowired
    private EvalScoreMagService evaScoreService;
    @Autowired
    private LeaderCriteriaService LearerCriteriaService;

    // 县处级领导一级页面
    @PostMapping("/leadsOne")
    public Result<HashMap<String, Object>> otherData(@RequestBody UserAppDTO param) {
        HashMap dataMap = new HashMap();
        String department = param.getDepartment();
        if (StringUtils.isBlank(department)) {
            return ResultUtils.getResults(Result.Status.ERROR, "单位名称空了，啊钢你少传参数了", null);
        }
        switch (department) {
            case "县委":
                department = "县委办";
                break;
            case "县人大":
                department = "人大办";
                break;
            case "县政府":
                department = "政府办";

                break;
            case "县政协":
                department = "政协办";
                break;
        }
        UserFilter userquery = new UserFilter();
        userquery.setIsLeader(1);
        userquery.setDepartment(department);
        userquery.setDel(0);
        List<UserFilter> userlists = userService.queryUsers(userquery);
        //String currentYear = getCurrentYear();
        for (UserFilter item : userlists) {
            double score = LearerCriteriaService.leaderTotalScore(item.getId());
            item.setFianlScore(DataUtil.formatNumberDouble(2,score));
        }
        /*
            计算排名
         */
        userlists = leadsRanks(userlists);
        dataMap.put("data", userlists);
        System.out.println("-------接口： /leadsOne");
        return ResultUtils.getResults(Result.Status.SUCCESS, "阿纲，你看看数据对不对", dataMap);
    }

    /**
     * 计算并列排名
     *
     * @return
     */
    private List<UserFilter> leadsRanks(List<UserFilter> userlists) {
        //计算排名 并列
        List<Map.Entry<Double, List<UserFilter>>> newDatas = userlists.stream().collect(Collectors.groupingBy(UserFilter::getFianlScore)).entrySet().stream()
                .sorted((o1, o2) -> -Double.compare(o1.getKey(), o2.getKey())).collect(Collectors.toList());
        int rank = 1;
        // 新计算并列排名
        for (Map.Entry<Double, List<UserFilter>> newData : newDatas) {
            int finalRank = rank;
            newData.getValue().forEach(o -> o.setRank(finalRank));
            rank = rank + newData.getValue().size();
        }
        return userlists;
    }


    /**
     * 002账号。我的考评
     *
     * @return
     */
    public List<UserFilter> getMyOnwDeptScore(String userTel) {
        UserFilter userInfo = getUserInfo(userTel);
        String departcode = userInfo.getDepartcode();//拿到单位编码，去获取他部门下所有的领导名单
        UserFilter userFilter1 = new UserFilter();
        userFilter1.setDepartcode(departcode);
        userFilter1.setIsLeader(1);
        userFilter1.setDel(0);
        List<UserFilter> allleads = userService.queryUsers(userFilter1);
        for (UserFilter item : allleads) {
            double score = LearerCriteriaService.leaderTotalScore(item.getId());
            item.setFianlScore(DataUtil.formatNumberDouble(2,score));
        }
        allleads = leadsRanks(allleads);
        return allleads;
    }
    /**
     * 县处级领导二级页面
     */
    @PostMapping("/leadsSecond")
    public Result<HashMap<String, Object>> leadsSecong(@RequestBody LeadersFilter param) {
        HashMap dataMap = new HashMap();
        List<LeadScoreDTO> dtos = new ArrayList<>();
        Long leadId = null;
        if (param.getRole().equals("slv")) { //002账号 自己的东西
            String userPhone = param.getUserPhone();
            List<UserFilter> myOnwDeptScore = getMyOnwDeptScore(userPhone);
            int maxRank = myOnwDeptScore.stream().mapToInt(UserFilter::getRank).max().getAsInt();
            List<UserFilter> owners = myOnwDeptScore.stream().filter(entity1 -> entity1.getUserPhone().equals(userPhone)).collect(Collectors.toList());
            int ownRank = owners.get(0).getRank();
            leadId = owners.get(0).getId();
            dataMap.put("ownerRank", ownRank + "/" + maxRank);
        } else {
            leadId = param.getLeadId();
            if (ObjectUtils.isBlank(leadId)) {
                return ResultUtils.getResults(Result.Status.ERROR, "leadid不能为空", null);
            }
        }
        List<EvaluateScoreEntity> scoreLists = LearerCriteriaService.eachItemScore(leadId);
        for (EvaluateScoreEntity item : scoreLists) {
            dtos.add(new LeadScoreDTO(DataUtil.formatNumberDouble(2,item.getFianlScore()), item.getAssessment(), item.getEvaId(),item.getCriteriaType() ,item.getConnects() ));
        }
        dataMap.put("data", dtos);
        double ownerscore = dtos.stream().mapToDouble(LeadScoreDTO::getFianlScore).sum();
        dataMap.put("ownerScore", DataUtil.formatNumberDouble(2,ownerscore));
        dataMap.put("leadId",leadId);
        System.out.println("/leadsSecond");
        return ResultUtils.getSuccessResults(dataMap);
    }


    /**
     * 县处级领导三级页面
     */
    @PostMapping("/leadsThree")
    public Result<HashMap<String, Object>> leadsThree(@RequestBody LeadersFilter param) {
        HashMap dataMap = new HashMap();
        List<ScoreDTO> dtos = new ArrayList<>();
        Long leadId = param.getLeadId();
        Long evaId = param.getEvaId();
        if (ObjectUtils.isBlank(leadId) || ObjectUtils.isBlank(evaId)) {
            return ResultUtils.getResults(Result.Status.ERROR, "leadid,evaId不能为空", null);
        }
        List<EvaluateScoreEntity> list = evaScoreService.queryEvainfo(evaId, leadId + "");
        for (EvaluateScoreEntity item : list) {
            EvaluateScoreEntity entity = LearerCriteriaService.detailItemScore(evaId, item.getCalculates(),item.getGrades());
            ScoreDTO dto = new ScoreDTO();
            dto.setRank(item.getRank());
            dto.setFinalScore( DataUtil.formatNumberDouble(2,entity.getFianlScore()) ); //得分
            dto.setIndexName(item.getAssessment());
            dto.setCalculates(item.getCalculates());
            dto.setGrades(StringUtils.isBlank(item.getGrades())?entity.getGrades():item.getGrades()); //档次
            dto.setSysCode(item.getSysCode());
            dto.setItemId(item.getItemid());
            dtos.add(dto);
        }
        dataMap.put("data", dtos);

        System.out.println("/leadsThree");
        return ResultUtils.getSuccessResults(dataMap);

    }


}
